package com.sxsihe.heartmate;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.sxsihe.heartmate.util.FileStates;
import com.sxsihe.heartmate.util.SharePreferenceUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import com.sxsihe.heartmate.view.expandable.ui.PinnedHeaderExpandableListView;
import org.w3c.dom.Text;

public class HistoryView extends FrameLayout implements View.OnClickListener,ExpandableListView.OnChildClickListener,
        ExpandableListView.OnGroupClickListener,
        PinnedHeaderExpandableListView.OnHeaderUpdateListener {
    private PinnedHeaderExpandableListView expandableListView;
    private ArrayList<DateItem> dateItems;
    private DateItemAdapter adapter;
    private List<Map<String, String>> listDatas;
    private Map<String, String> map;
    Button diagnose;
    TextView delete;
    TextView toggleAll;
    boolean selAll = false;
    Context context;
    SimpleDateFormat dateFormat;
    SimpleDateFormat timeFormat;
    ArrayList<String> checkPosition = new ArrayList<>();
    ArrayList<HashMap<String, String>> listItem;
    ArrayList<String> toBeOper = new ArrayList<String>();
    ArrayList<CheckBox> cbList = new ArrayList<CheckBox>();
    SharePreferenceUtil spu;
    private List<String> group ;
    private List<List<String>> child;

    public HistoryView(Context context) {
        super(context);
        this.context = context;
        if (spu == null) {
            spu = SharePreferenceUtil.getInstance(context);
        }

        dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        timeFormat = new SimpleDateFormat("HH:mm");
        View view = LayoutInflater.from(context).inflate(R.layout.main_tab_history, this);
//        diagnose = (Button) view.findViewById(R.id.diagnose);
//        diagnose.setOnClickListener(this);
        delete = (TextView) view.findViewById(R.id.delete);
        delete.setOnClickListener(this);
        toggleAll = (TextView) view.findViewById(R.id.toggleAll);
        toggleAll.setOnClickListener(this);
        initDatas();
        expandableListView = (PinnedHeaderExpandableListView) view.findViewById(R.id.expandablelist);
        adapter = new DateItemAdapter(context);
        expandableListView.setAdapter(adapter);

        // 展开所有group
        for (int i = 0, count = expandableListView.getCount(); i < count; i++) {
            expandableListView.expandGroup(i);
        }

        expandableListView.setOnHeaderUpdateListener(this);
        expandableListView.setOnGroupClickListener(this);
    }



    public void onLayout(boolean changed, int w, int h, int oldw, int oldh) {
        initDatas();
        if(FileStates.changed){
//            listItemAdapter.notifyDataSetChanged();
            FileStates.changed = false;
        }
        ((DateItemAdapter)expandableListView.getExpandableListAdapter()).notifyDataSetInvalidated();
        ((DateItemAdapter)expandableListView.getExpandableListAdapter()).notifyDataSetChanged();
        super.onLayout(changed, w, h, oldw, oldh);
     }


    public void initDatas() {
//        listItem.clear();
        File file = context.getFilesDir();
        File[] files = file.listFiles(new FilenameFilter() {
            String suffix = "data";

            @Override
            public boolean accept(File dir, String filename) {
                return filename.endsWith(suffix);
            }
        });
        String fileName = "";
        Pattern p = Pattern.compile("\\d+");
//        listView = (ExpandableListView) findViewById(android.R.id.list);
        this.group = new ArrayList<String>();
        this.child = new ArrayList<List<String>>();

        SimpleDateFormat format1 =  new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format2 =  new SimpleDateFormat("HH:mm:ss");

        Map<String,List<File>> map = new LinkedHashMap<>();
        for(int i=files.length-1;i>=0;i--){
            Date date = new Date(Long.parseLong(files[i].getName().replace(".data","")));
            String s = format1.format(date);
            if(map.containsKey(s)){
                map.get(s).add(files[i]);
            }else{
                List<File> l = new ArrayList<>();
                l.add(files[i]);
                map.put(s,l);
            }

        }



        dateItems = new ArrayList<>();
        DateItem dateItem = null;
        for(String s : map.keySet()){
            dateItem = new DateItem();
            dateItem.setTitle(s);
            List<TimeItem> timeItems = new ArrayList<>();
            for (int j = 0; j < map.get(s).size(); j++) {
                TimeItem timeItem = new TimeItem();
                long start = Long.parseLong(map.get(s).get(j).getName().replace(".data", ""));
                long end = map.get(s).get(j).lastModified();
                timeItem.setDuration1(format2.format(start) + "-" + format2.format(end));
                timeItem.setDuration2((end-start)/1000+1 + "秒");
                String line = "";
                try {
                     line = readLastLine(map.get(s).get(j),null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                int heartrate = 0;
                if(line!=null) {
                    String[] arr = line.split("\\|");
                    for (String str : arr) {
                        if (str.contains("averHeartRate")) {
                            heartrate = Integer.parseInt(str.split(":")[1]);
                        }
                    }
                }
                int status = 0;
                if(heartrate<60){
                    status = 1;
                }else if(heartrate>90){
                    status = 2;
                }

                timeItem.setStatus(status);
                timeItem.setHeartRate(heartrate);
                timeItem.setFileName(map.get(s).get(j).getName());
                timeItems.add(timeItem);
            }
            dateItem.setTimeItemList(timeItems);
            dateItems.add(dateItem);
        }

    }

    public static String readLastLine(File file, String charset) throws IOException {
        if (!file.exists() || file.isDirectory() || !file.canRead()) {
            return null;
        }
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            long len = raf.length();
            if (len == 0L) {
                return "";
            } else {
                long pos = len - 1;
                while (pos > 0) {
                    pos--;
                    raf.seek(pos);
                    if (raf.readByte() == '\n') {
                        break;
                    }
                }
                if (pos == 0) {
                    raf.seek(0);
                }
                byte[] bytes = new byte[(int) (len - pos)];
                raf.read(bytes);
                if (charset == null) {
                    return new String(bytes);
                } else {
                    return new String(bytes, charset);
                }
            }
        } catch (FileNotFoundException e) {
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (Exception e2) {
                }
            }
        }
        return null;
    }


    private void addInfo(String g,String[] childitem){
        this.group.add(g);
        List<String> list = new ArrayList<String>();
        for (String str : childitem) {
            list.add(str);
        }
        this.child.add(list);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete:
                if(toBeOper.size()==0){
                    return;
                }
                final AlertDialog myDialog = new AlertDialog.Builder(context).create();
                myDialog.show();
                myDialog.getWindow().setContentView(R.layout.delete_warning);
                myDialog.getWindow()
                        .findViewById(R.id.cancel)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                myDialog.dismiss();
                            }
                        });
                myDialog.getWindow()
                        .findViewById(R.id.confirm)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                deleteFile();
                                myDialog.dismiss();
                            }
                        });
//
                break;
            case R.id.toggleAll:
                toggleAllFile();
//                unDeleteFile();
                break;
        }
    }

    public void deleteFile() {
//        List<Map<String, String>> tmp = new ArrayList<Map<String, String>>();
//        for (Map<String, String> map : listItem) {
//            if ("true".equals(map.get("checked"))) {
//                new File(context.getFilesDir().getPath() + "/" + map.get("filename")).delete();
//                tmp.add(map);
//            }
//        }
        for(String filename :toBeOper){
            context.deleteFile(filename);
            Iterator<DateItem> iter = dateItems.iterator();
            while (iter.hasNext()){
                DateItem  dateItem = iter.next();
                if(dateItem.getTimeItemList().size()==0){
                    iter.remove();
                    continue;
                }
                Iterator tt = dateItem.getTimeItemList().iterator();
                while (tt.hasNext()){
                    TimeItem timeItem = (TimeItem) tt.next();
                    if(timeItem.getFileName().equals(filename)){
                        tt.remove();
                        break;
                    }
                }
            }
//            for(DateItem dateItem : dateItems){
//                if(dateItem.getTimeItemList().size()==0){
//                    dateItems.remove(dateItem);
//                    continue;
//                }
//                for(TimeItem timeItem:dateItem.getTimeItemList()){
//                    if(timeItem.getFileName().equals(filename)){
//                        dateItem.getTimeItemList().remove(timeItem);
//                        break;
//                    }
//                }
//            }
        }

        ((DateItemAdapter)expandableListView.getExpandableListAdapter()).notifyDataSetInvalidated();
        ((DateItemAdapter)expandableListView.getExpandableListAdapter()).notifyDataSetChanged();
        expandableListView.invalidate();
        this.invalidate();
        unDeleteFile();
    }
    public void unDeleteFile() {
        toBeOper.clear();
        for(int i=0;i<cbList.size();i++){
            cbList.get(i).setChecked(false);
        }
    }
    public void selAllFile() {
        toBeOper.clear();
        for(int i=0;i<cbList.size();i++){
            cbList.get(i).setChecked(true);
        }

        for(DateItem item : dateItems){
            for(TimeItem titem : item.getTimeItemList()){
                toBeOper.add(titem.getFileName());
            }
        }


    }


    public void toggleAllFile() {
        selAll = !selAll;
        if(selAll){
            toggleAll.setText("反选");
            selAllFile();
        }else{
            toggleAll.setText("全选");
            unDeleteFile();
        }
        ((DateItemAdapter)expandableListView.getExpandableListAdapter()).notifyDataSetInvalidated();
        ((DateItemAdapter)expandableListView.getExpandableListAdapter()).notifyDataSetChanged();
        expandableListView.invalidate();
        this.invalidate();
    }

    class DateItemAdapter extends BaseExpandableListAdapter {
        private Context context;
        private LayoutInflater inflater;

        public DateItemAdapter(Context context) {
            this.context = context;
            inflater = LayoutInflater.from(context);
        }

        // 返回父列表个数
        @Override
        public int getGroupCount() {
            return dateItems.size();
        }

        // 返回子列表个数
        @Override
        public int getChildrenCount(int groupPosition) {
            return dateItems.get(groupPosition).getTimeItemList().size();
        }

        @Override
        public Object getGroup(int groupPosition) {

            return dateItems.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return dateItems.get(groupPosition).getTimeItemList().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {

            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            DateItemHolder dateItemHolder = null;
            if (convertView == null) {
                dateItemHolder = new DateItemHolder();
                convertView = inflater.inflate(R.layout.history_group, null);
                dateItemHolder.textView = (TextView) convertView
                        .findViewById(R.id.group);
                convertView.setTag(dateItemHolder);
            } else {
                dateItemHolder = (DateItemHolder) convertView.getTag();
            }

            dateItemHolder.textView.setText(((DateItem) getGroup(groupPosition))
                    .getTitle());
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, final ViewGroup parent) {
            TimeItemHolder timeItemHolder = null;
            if (convertView == null) {
                timeItemHolder = new TimeItemHolder();
                convertView = inflater.inflate(R.layout.history_time_item, null);
                timeItemHolder.time_interval = (TextView)convertView.findViewById(R.id.time_interval);
                timeItemHolder.heart_status = (TextView)convertView.findViewById(R.id.heart_status);
                timeItemHolder.heart_rate = (TextView)convertView.findViewById(R.id.heart_rate);
                timeItemHolder.duration = (TextView)convertView.findViewById(R.id.duration);
                timeItemHolder.heart_status_icon = (ImageView)convertView.findViewById(R.id.heart_status_icon);
                timeItemHolder.time_layout = (RelativeLayout)convertView.findViewById(R.id.time_layout);
                timeItemHolder.detail_layout = (RelativeLayout)convertView.findViewById(R.id.detail_layout);
                timeItemHolder.playback = (Button)convertView.findViewById(R.id.playback);
                timeItemHolder.cb = (CheckBox)convertView.findViewById(R.id.checkbox);
                convertView.setTag(timeItemHolder);
            } else {
                timeItemHolder = (TimeItemHolder) convertView.getTag();
            }

            final TimeItem ti = ((DateItem) getGroup(groupPosition)).getTimeItemList().get(childPosition);
            timeItemHolder.time_interval.setText(ti.getDuration1());
            timeItemHolder.heart_rate.setText(ti.getHeartRate() + "");
            String status = "";
            timeItemHolder.heart_status_icon.setImageResource(R.drawable.his_status_bad);
            timeItemHolder.heart_status.setTextColor(Color.parseColor("#FA5830"));
            if(ti.getStatus()==0){
                status = "心率正常";
                timeItemHolder.heart_status_icon.setImageResource(R.drawable.his_status_good);
                timeItemHolder.heart_status.setTextColor(Color.parseColor("#1A96F5"));
            }
            else if(ti.getStatus()==1){
                status = "心率过缓";
            }
            else if(ti.getStatus()==2){
                status = "心率过速";
            }
            timeItemHolder.heart_status.setText(status);
            timeItemHolder.duration.setText(ti.getDuration2());

            timeItemHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        toBeOper.add(ti.getFileName());
                        cbList.add((CheckBox) buttonView);
                    }
                }
            });
            timeItemHolder.detail_layout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String filename = ti.getFileName();
                    Intent bintent = new Intent(HistoryView.this.getContext(), PlaybackActivity.class);
                    bintent.putExtra("filename", filename);
                    HistoryView.this.getContext().startActivity(bintent);
                }
            });
            timeItemHolder.playback.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String filename = ti.getFileName();
                    Intent bintent = new Intent(HistoryView.this.getContext(), PlaybackActivity.class);
                    bintent.putExtra("filename", filename);
                    HistoryView.this.getContext().startActivity(bintent);
                }
            });
            if(toBeOper.contains(ti.getFileName())){
                timeItemHolder.cb.setChecked(true);
            }else{
                timeItemHolder.cb.setChecked(false);
            }
            return convertView;
        }


        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }
    }

    class DateItemHolder {
        TextView textView;
    }

    class TimeItemHolder {
        RelativeLayout time_layout;
        RelativeLayout detail_layout;
        Button playback;
        TextView time_interval;
        TextView heart_status;
        TextView heart_rate;
        TextView duration;
        ImageView heart_status_icon;
        CheckBox cb;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        return false;
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

        return false;
    }

    @Override
    public View getPinnedHeader() {
        View headerView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.history_group, null);
        headerView.setLayoutParams(new AbsListView.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));

        return headerView;
    }

    @Override
    public void updatePinnedHeader(View headerView, int firstVisibleGroupPos) {
        DateItem firstVisibleGroup = (DateItem) adapter.getGroup(firstVisibleGroupPos);
        TextView textView = (TextView) headerView.findViewById(R.id.group);
        textView.setText(firstVisibleGroup.getTitle());
    }
}
